#include "camera.hpp"
#include "config.hpp"

uint image_waitting_time = 2000; // 图片录制间隔，单位为毫秒
uint video_duration = 10;        // 视频录制时长，单位为秒

uint frame_counter = 0;       // 记录图片数量
uint video_counter = 1;       // 拍摄的视频数量
uint video_frame_counter = 0; // 记录视频帧数

// 由于硬件性能限制，视频帧率和设想帧率有差别，需要根据camera_fps手动调整
uint video_fps = 10;
// 初始化视频写入器
string video_path = VIDEO_DIR + VIDEO_OUTPUT + "_" + to_string(video_counter) + VIDEO_EXTENSION;
int fourcc = VideoWriter::fourcc('a', 'v', 'c', '1');
VideoWriter v_writer(video_path, fourcc, video_fps, Size(WIDTH, HEIGHT));
uint max_video_frame_counter = video_duration * video_fps; // 最大视频帧数

/**
 * 重置图片和视频计数
 */
void format_camera_counter()
{
    // 重置视频
    video_uploaded = true;
    v_writer.release();
    video_counter = 1;
    video_frame_counter = 0;
    video_path = VIDEO_DIR + VIDEO_OUTPUT + "_" + to_string(video_counter) + VIDEO_EXTENSION;
    v_writer = VideoWriter(video_path, fourcc, video_fps, Size(WIDTH, HEIGHT));

    // 重置图片序列
    frame_counter = 0;
    {
        lock_guard<mutex> lock(frame_mutex);
        all_frames.clear();
    }
    cout << "Camera thread formatted." << endl;
}

/**
 * @brief 获取摄像头数据，并将图片保存到 all_frames 中
 * @param window 主窗口指针
 */
void camera_get(MainWindow *window)
{
    // 初始化摄像头
    VideoCapture cap(CAMERA_ID);
    if (!cap.isOpened())
    {
        cout << "Error opening video stream or file" << endl;
        return;
    }
    cap.set(CAP_PROP_FRAME_WIDTH, WIDTH);
    cap.set(CAP_PROP_FRAME_HEIGHT, HEIGHT);
    double camera_fps = 30; // 降低 FPS 以减少性能消耗。设想的视频帧率
    cap.set(CAP_PROP_FPS, camera_fps);
    // cout << "Actual Camera FPS: " << cap.get(CAP_PROP_FPS) << endl;

    // 初始化变量
    /**--------------------------------------------------------------------------------------- */
    // 图片相关
    Mat frame;
    // 视频相关
    double frame_interval_ms = 1000.0 / camera_fps; // 帧间隔

    // 初始化时间
    auto start_time_image = high_resolution_clock::now();
    auto start_time_video = high_resolution_clock::now();
    auto now_time = high_resolution_clock::now();
    while (running)
    {
        // 主要耗时操作
        cap >> frame;

        if (frame.empty())
        {
            cout << "Error: Empty frame captured." << endl;
            break;
        }
        Mat frame_copy = frame.clone();
        emit window->frame_ready(frame_copy);
        // 暂停线程
        if (suspend)
        {
            continue;
        }

        // 处理图片缓存逻辑
        /**--------------------------------------------------------------------------------------- */
        now_time = high_resolution_clock::now();
        auto duration_ms_image = duration_cast<milliseconds>(now_time - start_time_image).count();
        if (duration_ms_image >= image_waitting_time)
        {
            start_time_image = now_time;
            lock_guard<mutex> lock(frame_mutex);
            all_frames.push_back(frame);
            cout << "Get frame, counter: " << frame_counter << endl;
            cout << "Frame vector size: " << all_frames.size() << endl;
            frame_counter++;
        }
        /**--------------------------------------------------------------------------------------- */

        // 上一个视频上传完成，开始录制下一个视频
        /**--------------------------------------------------------------------------------------- */
        if (video_uploaded)
        {
            // 处理视频录制逻辑
            now_time = high_resolution_clock::now();
            auto duration_ms_video = duration_cast<milliseconds>(now_time - start_time_video).count();
            if (duration_ms_video >= frame_interval_ms)
            {
                start_time_video = now_time;
                v_writer.write(frame);
                video_frame_counter++;
                if (video_frame_counter >= max_video_frame_counter)
                {
                    v_writer.release();
                    video_frame_counter = 0;
                    if (video_counter >= MAX_VIDEO_NUMBER)
                    {
                        cout << "Video recording ended, total video number is " << video_counter << endl;
                        running = false;
                        break;
                    }
                    video_counter++;
                    cout << "Video recording finished, now video number is " << video_counter << endl;

                    // 更新视频路径
                    video_path = VIDEO_DIR + VIDEO_OUTPUT + "_" + to_string(video_counter) + VIDEO_EXTENSION;
                    v_writer = VideoWriter(video_path, fourcc, video_fps, Size(WIDTH, HEIGHT));
                    video_uploaded = false;
                }
            }
        }
        /**--------------------------------------------------------------------------------------- */
    }

    cap.release();
    cout << "Camera thread finished" << endl;
}

void test()
{
    auto start_time = high_resolution_clock::now();
    while (true)
    {
        auto now_time = high_resolution_clock::now();
        auto duration = duration_cast<milliseconds>(now_time - start_time).count();
        if (duration > 33)
        {
            start_time = now_time;
            cout << "duration: " << duration << " ms" << endl;
        }
    }
}
